﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web.Mvc;

namespace Cormant.Mvc.Web
{
    public class MvcGridViewBoundColumn : MvcGridViewColumn
    {
        public string DataField { get; set; }

        public override MvcTableCell CreateTableCell(MvcTable table, HtmlHelper html, object dataItem)
        {
            MvcTableCell cell = base.CreateTableCell(table, html, dataItem);
            cell.CssClass = this.ItemCssClass;
            if (!string.IsNullOrEmpty(this.DataField) && dataItem != null)
                cell.Text = this.GetDataItemFieldValue(dataItem);

            return cell;
        }

        protected string GetDataItemFieldValue(object dataItem)
        {
            if (!string.IsNullOrEmpty(this.DataField) && dataItem != null)
            {
                PropertyInfo property = dataItem.GetType().GetProperty(
                    this.DataField, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                if (property != null)
                {
                    object value = property.GetValue(dataItem, null);
                    return value == null ? string.Empty : value.ToString();
                }
            }
            return string.Empty;
        }
    }
}
